package com.acceptable.qucun.generic.aspect;

import com.acceptable.qucun.generic.exception.GenericExcetion;
import com.acceptable.qucun.generic.util.CodeUtil;
import com.acceptable.qucun.generic.util.result.error.GenericErrorResult;
import com.acceptable.qucun.generic.util.verify.FormatVerifyUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Map;

@Aspect
@Component
@Order(20)
public class RedisAspect {
    @Pointcut("execution(* com.acceptable.qucun.*.service.*Service.*ByVerifyCode(..) )")
    public void verifyCodePoint(){}

    @Pointcut("execution(* com.acceptable.qucun.*.service.*Service.*ByRedis(..) )")
    public void redisPoint(){}

    @Before("verifyCodePoint()")
    public void verifyCodeCheck(JoinPoint joinPoint){
        this.redisCheck(joinPoint);
        Object[] args = joinPoint.getArgs();
        Map<String, String> dataMap = (Map<String, String>) args[0];
        Map<String, String> redisMap = (Map<String, String>) CodeUtil.string2Object(dataMap.get("redis_map"));

        String redisVerifyCode = redisMap.get("verify_code");

        String verifyCode = dataMap.get("verify_code");
        // 验证码检查
        if(!verifyCode.equals(redisVerifyCode)){
            throw new GenericExcetion(GenericErrorResult.VERIFY_CODE_NOT_EXIST_ERROR);
        }
    }

    @Before("redisPoint()")
    public void redisCheck(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        if (!args[0].getClass().getSimpleName().contains("Map")){
            throw new GenericExcetion(GenericErrorResult.DATA_NOT_EXIST_ERROR);
        }
        Map<String, String> dataMap = (Map<String, String>) args[0];
        Map<String, String> redisMap = (Map<String, String>) CodeUtil.string2Object(dataMap.get("redis_map"));
        // redis数据检查
        if(FormatVerifyUtil.mapIsEmpty(redisMap))
            throw new GenericExcetion(GenericErrorResult.DATA_NOT_EXIST_ERROR);

        // 数据用途检查
        String redisUsage = redisMap.get("usage");
        String sendUsage = dataMap.get("usage");

        if(!sendUsage.equals(redisUsage))
            throw new GenericExcetion(GenericErrorResult.DATA_USAGE_ERROR);
    }
}
